package pers.qianyu.module.logging.service.impl;

import cn.hutool.core.io.*;
import cn.hutool.log.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import pers.qianyu.module.logging.exception.*;
import pers.qianyu.module.logging.service.*;

import java.io.*;

/**
 * 本地文件上传服务实现类
 *
 * @author mizzle rain
 * @date 2020年11月2日21:09:13
 */
@Service(value = "fileService")
public class LocalFileServiceImpl implements FileService {
    @Value("${path.uploads}")
    private String BUCKET;

    @Override
    public void upload(InputStream in, String fileName) {
        if (!FileUtil.exist(BUCKET)) {
            FileUtil.mkdir(BUCKET);
        }
        String storagePath = BUCKET + "/" + fileName;
        try (InputStream inputStream = in;
             FileOutputStream out = new FileOutputStream(storagePath)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            LogFactory.get().error("文件上传失败：{}", e.getMessage());
            throw new LoggingException(LoggingErrorCodeEnum.FILE_UPLOAD_FAILED);
        }
    }

    @Override
    public void upload(File file) {
        try {
            upload(new FileInputStream(file), file.getName());
        } catch (FileNotFoundException e) {
            LogFactory.get().error("文件上传失败：{}", e.getMessage());
            throw new LoggingException(LoggingErrorCodeEnum.FILE_UPLOAD_FAILED);
        }
    }
}
